package com.easy.service.impl;

import com.easy.bean.MessageBean;
import com.easy.bean.UserBean;
import com.easy.mapper.MessageDao;
import com.easy.mapper.UserDao;
import com.easy.service.MessageService;
import com.easy.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 消息服务实现类
 */
@Service
public class MessageServiceImpl implements MessageService {

    private static final Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);

    @Autowired
    private MessageDao messageDao; // 修复命名冲突

    @Autowired
    private UserDao userDao;

    @Override
    @Transactional
    public void sendPostPublishMessage(Integer userId, Integer postId, String postTitle) {
        MessageBean message = new MessageBean();
        message.setSenderId(0); // 系统消息，senderId为0
        message.setReceiverId(userId);
        message.setMsgType(MessageBean.TYPE_POST_PUBLISH);
        message.setPostId(postId);
        message.setContent("你的帖子《" + postTitle + "》已成功发布");
        message.setIsRead(0); // 未读

        messageDao.insert(message);
        logger.info("发送帖子发布消息成功，接收者ID:{}", userId);
    }

    /**
     * 发送帖子编辑消息
     */
    @Override
    @Transactional
    public void sendPostEditMessage(Integer userId, Integer postId, String postTitle) {
        MessageBean message = new MessageBean();
        message.setSenderId(0); // 系统消息
        message.setReceiverId(userId);
        message.setMsgType(MessageBean.TYPE_POST_EDIT);
        message.setPostId(postId);
        message.setContent("你的帖子《" + postTitle + "》已更新编辑");
        message.setIsRead(0); // 未读

        messageDao.insert(message);
        logger.info("发送帖子编辑消息成功，接收者ID:{}", userId);
    }

    @Override
    @Transactional
    public boolean sendMessage(MessageBean message) {
        try {
            return messageDao.insert(message) > 0;
        } catch (Exception e) {
            logger.error("发送消息失败", e);
            return false;
        }
    }

    @Override
    @Transactional
    public int deleteMessage(Integer id) {
        return messageDao.deleteById(id);
    }

    @Override
    @Transactional
    public boolean updateMessage(MessageBean message) {
        try {
            return messageDao.update(message) > 0;
        } catch (Exception e) {
            logger.error("更新消息失败", e);
            return false;
        }
    }

    @Override
    public MessageBean getMessageById(Integer id) {
        if (id == null) {
            logger.error("消息ID不能为空");
            return null;
        }
        try {
            return messageDao.selectById(id);
        } catch (Exception e) {
            logger.error("查询消息失败，ID:{}", id, e);
            return null;
        }
    }

    @Override
    public Page getMessagesByReceiverId(Integer receiverId, Integer pageNum, Integer pageSize) {
        Page page = new Page();
        page.setCurrent(pageNum);
        page.setLimit(pageSize);

        try {
            // 计算起始位置
            int start = (pageNum - 1) * pageSize;

            // 查询当前页数据
            List<MessageBean> messages = messageDao.selectByReceiverId(receiverId, start, pageSize);

            // 查询总记录数
            int totalCount = messageDao.countByReceiverId(receiverId);

            // 设置分页数据
            page.setData(messages);
            page.setCount(totalCount);

            return page;
        } catch (Exception e) {
            logger.error("分页查询消息失败，接收者ID:{}", receiverId, e);
            return page;
        }
    }

    @Override
    public Page getMessagesByTypeAndReceiver(Integer receiverId, String msgType, Integer pageNum, Integer pageSize) {
        Page page = new Page();
        page.setCurrent(pageNum);
        page.setLimit(pageSize);

        try {
            // 计算起始位置
            int start = (pageNum - 1) * pageSize;

            // 查询当前页数据
            List<MessageBean> messages = messageDao.selectByTypeAndReceiverWithPage(msgType, receiverId, start, pageSize);

            // 查询总记录数
            int totalCount = messageDao.countByTypeAndReceiver(msgType, receiverId);

            // 设置分页数据
            page.setData(messages);
            page.setCount(totalCount);

            return page;
        } catch (Exception e) {
            logger.error("按类型分页查询消息失败，接收者ID:{}, 类型:{}", receiverId, msgType, e);
            return page;
        }
    }

    @Override
    public int getUnreadCount(Integer receiverId) {
        try {
            return messageDao.countUnreadByReceiverId(receiverId);
        } catch (Exception e) {
            logger.error("查询未读消息数量失败，接收者ID:{}", receiverId, e);
            return 0;
        }
    }

    @Override
    public int getUnreadCountByType(Integer receiverId, String msgType) {
        try {
            // 先获取该类型的所有消息
            List<MessageBean> messages = messageDao.selectByTypeAndReceiver(msgType, receiverId);

            // 统计未读消息数量
            int unreadCount = 0;
            for (MessageBean message : messages) {
                if (message.getIsRead() == 0) {
                    unreadCount++;
                }
            }

            return unreadCount;
        } catch (Exception e) {
            logger.error("按类型查询未读消息数量失败，接收者ID:{}, 类型:{}", receiverId, msgType, e);
            return 0;
        }
    }

    @Override
    @Transactional
    public boolean markMessagesAsRead(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        try {
            return messageDao.markAsRead(ids) > 0;
        } catch (Exception e) {
            logger.error("标记消息为已读失败", e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean markAllMessagesAsRead(Integer receiverId) {
        try {
            return messageDao.markAllAsRead(receiverId) > 0;
        } catch (Exception e) {
            logger.error("标记所有消息为已读失败，接收者ID:{}", receiverId, e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean markMessagesAsReadByType(Integer receiverId, String msgType) {
        try {
            // 获取该类型的所有消息ID
            List<MessageBean> messages = messageDao.selectByTypeAndReceiver(msgType, receiverId);

            if (messages.isEmpty()) {
                return true;
            }

            // 提取消息ID
            List<Integer> ids = messages.stream()
                    .map(MessageBean::getId)
                    .collect(java.util.stream.Collectors.toList());

            // 标记为已读
            return messageDao.markAsRead(ids) > 0;
        } catch (Exception e) {
            logger.error("按类型标记消息为已读失败，接收者ID:{}, 类型:{}", receiverId, msgType, e);
            return false;
        }
    }

    @Override
    @Transactional
    public void sendLikeMessage(Integer postAuthorId, Integer likerId, Integer postId, Integer giveId) {
        // 获取点赞用户信息
        UserBean liker = userDao.get(likerId);
        if (liker == null) {
            logger.warn("点赞用户不存在，ID:{}", likerId);
            return;
        }

        // 创建点赞消息
        MessageBean message = new MessageBean();
        message.setSenderId(likerId);
        message.setReceiverId(postAuthorId);
        message.setMsgType("LIKE");
        message.setPostId(postId);
        message.setGiveId(giveId);
        message.setContent(liker.getUserNickname() + " 赞了你的帖子");
        message.setIsRead(0);

        // 发送消息
        messageDao.insert(message);
        logger.info("发送点赞消息成功，接收者ID:{}", postAuthorId);
    }

    @Override
    @Transactional
    public void sendCommentMessage(Integer postAuthorId, Integer commenterId, Integer postId,
                                   Integer commentId, String commentContent) {
        // 获取评论用户信息
        UserBean commenter = userDao.get(commenterId);
        if (commenter == null) {
            logger.warn("评论用户不存在，ID:{}", commenterId);
            return;
        }

        // 创建评论消息
        MessageBean message = new MessageBean();
        message.setSenderId(commenterId);
        message.setReceiverId(postAuthorId);
        message.setMsgType("COMMENT");
        message.setPostId(postId);
        message.setCommentId(commentId);

        // 截取评论内容前30个字符作为预览
        String preview = commentContent.length() > 30 ?
                commentContent.substring(0, 30) + "..." : commentContent;
        message.setContent(commenter.getUserNickname() + " 评论了你的帖子: " + preview);
        message.setIsRead(0);

        // 发送消息
        messageDao.insert(message);
        logger.info("发送评论消息成功，接收者ID:{}", postAuthorId);
    }
}